const http = require('http')
const fs = require('fs')
const server = http.createServer((request, response) => {
    // response.end('hello ...')
    const { url, method ,headers} = request
    //观察cookie的存在
    console.log('cookie',request.headers.cookie)
    if (url === '/' && method === 'GET'){
        // 静态页面服务
        fs.readFile('index.html',(err, data) => {
            response.statusCode = 200
            response.setHeader('Content-Type','text/html')
            response.end(data)
        })
    }else if(url === '/api/users' && method === 'GET'){
        // Ajax服务
        response.setHeader('Set-Cookie','cookie1=va222')//设置cookie
        // response.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000')//允许跨域
        response.writeHead(200,{
            'Content-Type': 'application/json',
            // "Access-Control-Allow-Credentials":"true"//允许跨域的cookie
        })
        response.end(JSON.stringify({
            name : 'laowang2222'
        }))
    }else if(method === 'GET' && headers.accept.indexOf('image/*') !== -1){
        // 图片文件服务
        fs.createReadStream("."+url).pipe(response)
    }else if(method == 'OPTIONS' && url=='/api/users'){//允许预检请求
        response.writeHead(200,{
            // "Access-Control-Allow-Origin":"http://localhost:3000",
            // "Access-Control-Allow-Headers":"X-Token,Content-Type",//允许携带额外header参数
            // "Access-Control-Allow-Methods":"PUT",
            // "Access-Control-Allow-Credentials":"true"
        })
        response.end()
    }else if(method ==='POST' && url=="/api/save"){
        let reqData = [];
        let size = 0;
        request.on('data',data=>{
            console.log('>>>req on',data)
            reqData.push(data);
            size += data.length;
        });
        request.on('end',function () {
            console.log('end');
            const data = Buffer.concat(reqData,size);
            console.log('data',size,data.toString())
            response.end(`formdata:${data.toString()}`)
        })
    }

})
server.listen(4000)